<!-- 基础设置 img上传-->
<template>
  <ele-modal
    width="80%"
    :inner="false"
    :centered="true"
    :visible="visible"
    :close-on-click-modal="true"
    custom-class="ele-dialog-form"
    :title="title"
    append-to-body
    @update:visible="updateVisible"
    v-if="visible"
  >
    <div >
      <el-row >
        <!-- :xl="18" :lg="18" :md="18" :sm="18" :xs="24" -->
        <el-col>
          <div class="conter">
            <div class="bnt acea-row row-middle">
              <el-col >
                <el-button
                  type="primary"
                  :disabled="checkPicList.length === 0"
                  @click="checkPics"
                  class="mr10"
                  v-if="isShow !== 0"
                >使用选中图片</el-button
                >
                 <!--关闭自动上传-->
                <!--<el-upload
                  style="margin-top: 1px; display: inline-block"
                  class="mr10 mb10"
                  action=""
                  :on-change="onUpload"
                  multiple
                  :auto-upload="false"
                  :file-list="fileList">
                  <el-button type="primary">上传图片</el-button>
                </el-upload>-->
                <!--:http-request="handleHttpRequest"-->
                <!--暂不使用多行 :multiple="true"-->
                <el-upload
                  :auto-upload="false"
                  :show-upload-list="false"
                  class="mr10 mb10"
                  :before-upload="beforeUpload"
                  :data="uploadData"
                  :show-file-list="false"
                  accept=".jpg,.jpeg,.png"
                  :format="['jpg', 'jpeg', 'png', 'gif']"
                  action=""
                  :on-change="onUpload"
                  style="margin-top: 1px; display: inline-block"
                >
                  <el-button type="primary">上传图片</el-button>
                </el-upload>
                <!--<Button type="success" @click.stop="add" class="mr10">添加分类</Button>-->
                <el-button
                  type="error"
                  class="mr10"
                  :disabled="checkPicList.length === 0"
                  @click.stop="editPicList('图片')"
                >删除图片</el-button>
              </el-col>
            </div>

            <!--图片list-->
            <div class="pictrueList acea-row">
              <el-row :gutter="24" class="conter">
                <div v-show="isShowPic" class="imagesNo">
                  <el-icon type="ios-images" size="60" color="#dbdbdb" />
                  <span class="imagesNo_sp">图片库为空</span>
                </div>
                <div class="acea-row mb10">
                  <div
                    class="pictrueList_pic mr10 mb10"
                    v-for="(item, index) in pictrueList"
                    :key="index"
                    @mouseenter="enterMouse(item)"
                    @mouseleave="enterMouse(item)"
                  >
                    <el-badge :value="item.num" style="position: absolute;right: 12px;top: 16px;z-index: 9999;" v-if="item.num > 0" type="primary" :max="99"  >
                    </el-badge>
                    <el-image
                      :class="item.isSelect ? 'on' : ''"
                      :src="item.imgUrl"
                      lazy
                      @click.stop="changImage(item, index, pictrueList)"
                    />
                    <div
                      style="
                      display: flex;
                      align-items: center;
                      justify-content: space-between;
                    "
                      @mouseenter="enterLeave(item)"
                      @mouseleave="enterLeave(item)"
                    >
                      <p style="width: 80%" v-if="!item.isEdit">
                        {{ item.editName }}
                      </p>
                      <el-input
                        size="small"
                        style="width: 80%"
                        type="text"
                        v-model="item.real_name"
                        v-else
                        @on-blur="bindTxt(item)"
                      />
                      <span
                        class="iconfont iconbianji1"
                        @click="item.isEdit = !item.isEdit"
                        v-if="item.isShowEdit"
                      ></span>
                    </div>
                    <div
                      class="nameStyle"
                      v-show="item.realName && item.real_name"
                    >
                      {{ item.real_name }}
                    </div>
                  </div>
                </div>

                <p class="number" >
                  <el-pagination
                    @current-change="pageChange"
                    :page-size="18"
                    layout="total, prev, pager, next, jumper"
                    :total="total">
                  </el-pagination>
                </p>
              </el-row>
            </div>
          </div>
        </el-col>
      </el-row>
    </div>
  </ele-modal>
</template>

<script>
  import { oemOssSignature } from '@/api/creatCenter/material';
  import {delFile, fileListApi, saveImg} from "@/api/agent/pointAllocation";
  import {getToken} from "@/utils/token-util";
  import axios from "axios";
  import NewSponsor from "@/views/explosiveCode/largeScreenLottery/components/new-sponsor";

    export default {
      name: "uploadImg",
      props: {
        // 弹窗是否打开
        visible: Boolean,
        title: {
          type: String,
          default: "选择图片",
        },
        isChoice: {
          type: String,
          default: "",
        },
        gridBtn: {
          type: Object,
          default: null,
        },
        gridPic: {
          type: Object,
          default: null,
        },
        isShow: {
          type: Number,
          default: 1,
        },
        pageLimit: {
          type: Number,
          default: 0,
        },
      },
      data(){
          return{

            // 懒加载
            value: undefined,
            initValue: undefined,
            showEdit:false,
            editData:null,
            parentId:'',
            spinShow: false,
            fileUrl:  "/file/upload",
            modalPic: false,
            treeData: [],
            treeData2: [],
            pictrueList: [],
            uploadData: {}, // 上传参数
            checkPicList: [],
            uploadName: {
              name: "",
            },
            FromData: null,
            treeId: 0,
            isJudge: false,
            buttonProps: {
              type: "default",
              size: "small",
            },
            fileData: {
              pid: 0,
              type:1,
              page: 1,
              limit: this.pageLimit || 18,
            },
            total: 0,
            pids: 0,
            list: [],
            modalTitleSs: "",
            isShowPic: false,
            header: {},
            ids: [], // 选中附件的id集合
            fileList:[]
          }
      },
      mounted() {
        this.getFileList();
      },
      methods:{
          show(){
            this.getFileList();
          },
        // 点击使用选中图片
        checkPics() {
          if (this.isChoice === "单选") {
            console.log('this.checkPicList',this.checkPicList)
            if (this.checkPicList.length > 1)
              return this.$message.warning("最多只能选一张图片");
            this.$emit("getPic", this.checkPicList[0]);
          } else {
            debugger;
            let maxLength = this.$route.query.maxLength;
            if (
              maxLength != undefined &&
              this.checkPicList.length > Number(maxLength)
            )
              return this.$message.warning("最多只能选" + maxLength + "张图片");
            this.$emit("getPicD", this.checkPicList);
          }
          console.log('清空==========')
          // 清空
          this.checkPicList = [];
        },
        enterMouse(item) {
          item.realName = !item.realName;
        },
        enterLeave(item) {
          item.isShowEdit = !item.isShowEdit;
        },

        // 选中图片
        changImage(item, index, row) {
          let activeIndex = 0;
          if (!item.isSelect) {
            item.isSelect = true;
            this.checkPicList.push(item);
          } else {
            item.isSelect = false;
            this.checkPicList.map((el, index) => {
              if (el.id == item.id) {
                activeIndex = index;
              }
            });
            this.checkPicList.splice(activeIndex, 1);
          }

          this.ids = [];
          this.checkPicList.map((item, i) => {
            this.ids.push(item.id);
          });
          this.pictrueList.map((el, i) => {
            if (el.isSelect) {
              console.log("el.isSelect",el.isSelect)
              this.checkPicList.filter((el2, j) => {
                if (el.id == el2.id) {
                  el.num = j + 1;
                }
              });
            } else {
              el.num = 0;
            }
          });
        },

        // 删除图片
        editPicList(tit) {
          this.tits = tit;
          delFile({ids:this.ids})
            .then((msg) => {
              this.$message.success('删除成功');
              this.getFileList();
              console.log('清空==========')
              this.checkPicList = [];
            })
            .catch((e) => {
              this.$message.error(e);
            });
        },
        // 上传之前
        beforeUpload(file) {
          // if (file.size > 2097152) {
          //   this.$Message.error(file.name + "大小超过2M!");
          // } else
          // if (!/image\/\w+/.test(file.type)) {
          //   this.$message.error("请上传以jpg、jpeg、png等结尾的图片文件"); //FileExt.toLowerCase()
          //   return false;
          // }
          // this.uploadData = {
          //   pid: this.treeId,
          // };
          // let promise = new Promise((resolve) => {
          //   this.$nextTick(function () {
          //     resolve(true);
          //   });
          // });
          // return promise;
        },
        // 上传成功
        handleSuccess(res, file, fileList) {
        },
        /* 上传 */
        onUpload(file) {
          if (file.status !== 'ready') return // 阻止上传成功的触发
          console.log("进入上传file············",file)
          this.uploadData=file
          this.fileList.push(this.uploadData)
          console.log('this.fileList',this.fileList,this.fileList.length)
          setTimeout(()=>{
            this.uploadImg()
          },200)
        },
        async uploadImg(){
          if(this.fileList.length < 1) {
            console.log("请选择文件后提交")
            this.$message.error('请选择文件后提交');
            return
          }
          console.log("this.fileListthis.fileListthis.fileList",this.fileList)
          this.data = await oemOssSignature()
          for(let i=0;i<this.fileList.length;i++){
            let file = this.fileList[i].raw
            console.log(file)
            let filename=file.name;
            let markIndex=(filename).lastIndexOf('.');
            let suffix=filename.substring(markIndex)
            let date=new Date().getTime();
            // 构建请求参数
            let param = new FormData()
            param.append("key", this.data.dir + date+suffix)
            param.append("policy", this.data.policy)
            param.append("OSSAccessKeyId", this.data.accessId)
            param.append("success_action_status", '200')
            // param.append("callback",  this.data.callback)     //回调（not)
            param.append("signature", this.data.signature)
            param.append("file", file, file.name)
            param.append('success_action_status', '200')
            let config = {
              headers: {
                'Access-Control-Allow-Origin': '*',
                'x-oss-callback-Authorization': getToken()
              }
            }
            console.log("suffix",suffix)
            axios.post(this.data.host, param, config).then(res => {
              if(res.status==200){
                console.log('this.data.host',this.data.host+'/'+date+suffix)
                let url=this.data.host+'/'+date+suffix;
                let type=file.type;
                console.log('file.type',file.type)
                // 清空已上传的文件列表（该方法不支持在 before-upload 中调用）
                // this.$refs['upload'].clearFiles()
                this.fileList=[]
                this.registerMedias(url,type);
                console.log('url',url)
              }
              else{
                this.$message.error('上传失败');
              }

            }).catch(err => {
              console.log(err)
            })
          }
        },
        // 上传保存到数据库
        registerMedias(url) {
          saveImg({
            imgUrl:url,//上传阿里云生成的地址
            oemId:this.$store.state.user.info.oemId   //代理id
          })
            .then((data) => {
              this.getFileList();
              this.checkPicList = [];  //清空所选中的图片数据
              this.$message.success('上传成功');
            })
            .catch((e) => {
              this.$message.error(e.msg);
            });
        },
        pageChange(index) {
          this.fileData.page = index;
          this.getFileList();
          console.log("清空========")
          this.checkPicList = [];
        },
        // 文件列表
        getFileList() {
          // this.fileData.pid = this.treeId;
          let preview={
            oemId:this.$store.state.user.info.oemId,
            limit:10,
            page:1,
            pid:this.treeId
          }

          fileListApi(preview)
            .then(async (res) => {
              console.log("res",res)

              res.list.forEach((el) => {
                el.isSelect = false;
                el.isEdit = false;
                el.isShowEdit = false;
                el.realName = false;
                el.num = 0;
                // 获取名称
                this.editName(el);
              });
              this.pictrueList = res.list;
              console.log("this.pictrueList===================",this.pictrueList)

              if (this.pictrueList.length) {
                this.isShowPic = false;
              } else {
                this.isShowPic = true;
              }
              this.total = res.count;
            })
            .catch((res) => {
              this.$message.error(res.msg);
            });
        },
        editName(item) {
          /*let n =item.imgUrl
          let spliceLength2 = n.lastIndexOf('/');
          congsole.log('pathType11111=========',pathType)

          let pathType = n.slice(spliceLength2 + 1);
          congsole.log('pathTypeeeeee333333=========',pathType)
          item.editName = pathType*/
          item.editName = item.imgUrl
          // let it = item.imgUrl.split(".");
          // let it1 = it[1] == undefined ? [] : it[1];
          // let len = it[0].length + it1.length;
          // item.editName =
          //   len < 10
          //     ? item.imgUrl
          //     : item.imgUrl.substr(0, 2) + "..." + item.imgUrl.substr(-5, 5);
        },
        /* 更新visible */
        updateVisible(value) {
          this.checkPicList = [];
          this.$emit('update:visible', value);
        },
      }
    }
</script>

<style scoped lang="stylus">
  .nameStyle {
    position: absolute;
    white-space: nowrap;
    z-index: 9;
    background: #eee;
    height: 20px;
    line-height: 20px;
    color: #555;
    border: 1px solid #ebebeb;
    padding: 0 5px;
    left: 56px;
    bottom: -18px;
  }

  .acea-row, .c_row-item {
    display: -webkit-box;
    display: -ms-flexbox;
    display: flex;
  }
  .acea-row {
    -webkit-box-lines: multiple;
    -moz-box-lines: multiple;
    -o-box-lines: multiple;
    -ms-flex-wrap: wrap;
    flex-wrap: wrap;
  }

  .iconbianji1 {
    font-size: 13px;
  }

  /deep/.ivu-badge-count {
    margin-top: 18px !important;
    margin-right: 19px !important;
  }

  /deep/ivu-tree-title-selected:hover {
    color: #2D8cF0 !important;
  }

  /deep/.ivu-tree-title {
    padding: 0;
    // width: 200px;
    width: 100%;

  }

  /deep/.ivu-span {
    padding: 0;
    display: flex !important;
    justify-content: space-between;
  }

  /deep/.ivu-tree ul li {
    margin: 0;
  }

  /deep/.ivu-tree-arrow {
    width: 17px;
    color: #626262;
  }

  /deep/.ivu-span:hover {
    color: #2D8cF0 !important;
  }

  /deep/.ivu-tree-arrow i {
    vertical-align: bottom;
  }

  .Nav /deep/.ivu-icon-ios-arrow-forward:before {
    content: '\F341' !important;
    font-size: 20px;
  }

  /deep/.ivu-btn-icon-only.ivu-btn-small {
    padding: unset !important;
  }

  .selectTreeClass {
    background: #d5e8fc;
  }

  .treeBox {
    width: 100%;
    height: 100%;

    >>> .ivu-tree-title-selected, .ivu-tree-title-selected:hover {
      color: #2D8cF0 !important;

    }

    >>> .ivu-btn-icon-only {
      width: 20px !important;
      height: 20px !important;
    }

    >>> .ivu-tree-title:hover {
      color: #2D8cF0 !important;

    }
  }

  .pictrueList_pic {
    position: relative;
    width: 100px;
    cursor: pointer;

    .el-image {
      width: 100%;
      height: 100px;
    }

    p {
      overflow: hidden;
      text-overflow: ellipsis;
      white-space: nowrap;
      height: 20px;
      text-align: center;
    }

    .number {
      height: 33px;
    }

    .number {
      position: absolute;
      right: 20px;
      top: 15px;
    }
  }

  .trees-coadd {
    width: 100%;
    border-radius: 4px;
    overflow: hidden;
    position: relative;

    .scollhide {
      overflow-x: hidden;
      overflow-y: scroll;
      padding: 10px 0 10px 0;
      box-sizing: border-box;

      .trees {
        width: 100%;
        height: 374px;
      }
    }

    .scollhide::-webkit-scrollbar {
      display: none;
    }
  }

  .treeSel >>>.ivu-select-dropdown-list {
    padding: 0 5px !important;
    box-sizing: border-box;
    width: 200px;
  }

  .imagesNo {
    display: flex;
    justify-content: center;
    flex-direction: column;
    align-items: center;
    margin: 65px 0;

    .imagesNo_sp {
      font-size: 13px;
      color: #dbdbdb;
      line-height: 3;
    }
  }

  .Modal {
    width: 100%;
    height: 100%;
    background: #fff !important;
  }

  .Nav {
    width: 100%;

  }

  .colLeft {
    padding-right: 0 !important;
    height: 100%;
  }

  .conter {
    width: 100%;
    height: 100%;
    margin-left: 0 !important;
  }

  .conter .bnt {
    width: 100%;
    padding: 0 13px 10px 8px;
    box-sizing: border-box;
  }

  .conter .pictrueList {
    padding-left: 6px;
    width: 100%;
    /*max-width: 1200px;*/
    overflow-x: hidden;
    overflow-y: auto;
    /*height: 300px;*/
  }

  .conter .pictrueList .el-image {
    width: 100%;

  }

  .conter .pictrueList .el-image.on {
    border: 2px solid #5FB878;
  }

  .conter .footer {
    padding: 0 20px 10px 20px;
  }

  .demo-badge {
    width: 42px;
    height: 42px;
    background: transparent;
    border-radius: 6px;
    display: inline-block;
  }

  .bnt /deep/ .ivu-tree-children {
    padding: 5px 0;
  }

  .mb10 {
    margin-bottom: 15px!important;
  }
  .mr10 {
    margin-right: 10px;
  }

  .trees-coadd /deep/ .ivu-tree-children .ivu-tree-arrow {
    line-height: 25px;
  }

  .el-checkbox__inner::after {
    transition: none!important;
  }

  .el-dialog__wrapper{
    &.dialog-fade-enter-active{
      -ms-animation:none;
    }
    &.dialog-fade-leave-active{
      -ms-animation:none;
    }
  }

</style>
